#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'python'
__mtime__ = '18-9-8'
# code is far away from bugs with the god animal protecting ~
"""

import logging
from logging.handlers import RotatingFileHandler

from flask import Flask
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import CSRFProtect, csrf
from redis import StrictRedis

from config import config, Conifg
from info.utils.common import filter_series, RegexConverter

db = SQLAlchemy()
redis_server = StrictRedis(host=Conifg.REDIS_IP, port=Conifg.REDIS_PORT) #, decode_responses=True


def createApp(config_name):
	app = Flask(__name__)
	app.config.from_object(config[config_name])
	db.init_app(app)
	Session(app)
	CSRFProtect(app)

	logging.basicConfig(level=config[config_name].LOGGER_LEVEL)
	log_handler = RotatingFileHandler("logs/log", maxBytes=1048576, backupCount=5)
	log_formatter = logging.Formatter("%(name)s %(levelname)s %(filename)s %(lineno)s : %(message)s")
	log_handler.setFormatter(log_formatter)
	logging.getLogger().addHandler(log_handler)

	# 在每次请求后，增加设置cookie，以防止CSRF
	@app.after_request
	def after_request(response):
		response.set_cookie("csrf_token",csrf.generate_csrf())
		return response

	# 增加模板过滤器
	app.add_template_filter(filter_series,"filter_series")
	# 增加re路由转换器，如“/news/<re:\d{3}>"
	app.url_map.converters['re'] = RegexConverter

	from .modules.index import bp_index
	app.register_blueprint(bp_index)
	from .modules.passport import bp_passport
	app.register_blueprint(bp_passport)
	from .modules.users import bp_users
	app.register_blueprint(bp_users, url_prefix="/users")
	from .modules.admin import bp_admin
	app.register_blueprint(bp_admin, url_prefix="/admin")

	return app


if __name__ == '__main__':
	pass
